home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 17377 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: news.sprintlink.net!datalytics!usenet
  2. From: Rob Stewart <stew@datalytics.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: [Q] Recursive mechanism
  5. Date: Mon, 15 Apr 1996 13:01:20 -0400
  6. Organization: Datalytics, Inc
  7. Message-ID: <317280E0.1340@datalytics.com>
  8. References: <4khu5s$oop@dfw-ixnews1.ix.netcom.com>
  9. NNTP-Posting-Host: 204.62.224.71
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (WinNT; I)
  14.  
  15. stefmit@ix.netcom.com wrote:
  16. > Could anybody explain the mechanism behind the following (broken) code:
  17. > in a linked list:
  18. > void List<type> :: reverse (Node<type> *p) const
  19. > { while ( p!= 0)
  20. >         reverse (p -> next);
  21. >         cout << p -> data; }
  22. > that is, replacing if with while to get an infinite loop?
  23. > How does it differ in the way of processing from the correct usage of if?
  24. > NOTE: the first call is made with reverse(first_element_pointer)
  25. > Thanks.
  26.  
  27. I'm not quite sure what your question is, but I think you're 
  28. asking why while makes this an infinite loop and why if 
  29. wouldn't.  If p is non-zero, the loop is, simply:
  30.  
  31. while (p);
  32.  
  33. Since the body of the loop doesn't change the value of p, the 
  34. condition never changes, resulting in an infinite loop.  
  35. Obviously, using if only checks the condition once, regardless 
  36. of the outcome, so it isn't an infinite loop.  Now, at this 
  37. point, I have to assume there is more to this function than you 
  38. have posted here.  Otherwise, "reverse" does nothing but print 
  39. the data of each node from p to the end of the list.
  40.  
  41. Clearly, this code:
  42.  
  43. void List<type>::reverse(Node<type> *p) const
  44. {
  45.    if (p)
  46.    {
  47.       reverse(p->next);
  48.       cout << p->data;
  49.    }
  50. }
  51.  
  52. implements the desired functionality of reverse as presently 
  53. given.
  54.  
  55. -- 
  56. Robert Stewart        | My opinions are usually my own.
  57. Datalytics, Inc.    | stew@datalytics.com
  58.